package com.gupao.p7store.common.utils.file;

import com.gupao.p7store.common.utils.StringUtils;
import com.gupao.p7store.common.utils.io.IoTools;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.AesKeyStrength;
import net.lingala.zip4j.model.enums.EncryptionMethod;

import java.io.File;

/**
 * desc:    zip 操作类
 *
 * @author: dengbicheng
 * @date: 2021-12-13 10:53
 * @version: v 1.0.0
 */
@Slf4j
public class ZipUtils {

    public static void doGenerateZip(File folder1, String zipPassword) {
        ZipParameters zipParameters = new ZipParameters();
        // 压缩包加密
        zipParameters.setEncryptFiles(StringUtils.isNotEmpty(zipPassword));
        zipParameters.setEncryptionMethod(EncryptionMethod.AES);
        zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
        File folder = new File(folder1.toString());
        if (!folder.exists()) {
            folder.mkdir();
        }

        ZipFile zipFile = null;
        if(StringUtils.isNotEmpty(zipPassword)) {
            zipFile = new ZipFile(folder1 + FileFormat.ZIP, zipPassword.toCharArray());
        } else {
            zipFile = new ZipFile(folder1 + FileFormat.ZIP);
        }


        try {
            zipFile.addFolder(folder, zipParameters);
        } catch (ZipException e) {
            e.printStackTrace();
        } finally {
            IoTools.close(zipFile);
        }
    }

    public static void doGenerateZip(File folder1) {
        doGenerateZip(folder1, null);
    }

}
